﻿#region NeoPatterns
// 
// NeoPatterns framework is released under LGPLv3 license.
// See http://www.opensource.org/licenses/lgpl-3.0.html for more details.
// 
// Please visit http://neopatterns.wikidot.com for more information about NeoPatterns
// 
// Copyright (c) Pascal Craponne 2008
// 
#endregion

using NeoPatterns.Core.Aop;
using NeoPatterns.Utility;

namespace NeoPatterns.Patterns.Proxy
{
    /// <summary>
    /// The proxy advisor is not instance related. It takes the instance (proxy) as parameter
    /// It is used by AspectProxy (which is instance related)
    /// </summary>
    public class ProxyAdvisor : ClaimingAdvisor<object>
    {
        /// <summary>
        /// Returns current proxy target (stored in claims space)
        /// </summary>
        /// <param name="proxy"></param>
        /// <returns></returns>
        public object GetTarget(object proxy)
        {
            return GetClaims(proxy);
        }

        /// <summary>
        /// Sets proxy target (in claims space)
        /// </summary>
        /// <param name="proxy"></param>
        /// <param name="target"></param>
        public void SetTarget(object proxy, object target)
        {
            SetClaims(proxy, target);
        }

        /// <summary>
        /// The advisor changes the proxy target
        /// </summary>
        /// <param name="invocation"></param>
        public override void Advise(IInvocation invocation)
        {
            var target = invocation.GetClaims<object>(Claims);
            invocation.ReturnValue = invocation.TargetMethod.Invoke(target, invocation.Parameters);
        }

        public override void InitializeClaims(object target)
        {
            // by default, the target is identical to the proxy
            SetTarget(target, target);
        }
    }
}